package com.demo.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo.service.StudentManager;
import com.util.HttpConnection;
import com.util.ZookeeperClient;

@Controller
@RequestMapping("/student")

public class StudentController {
	private Logger logger = LoggerFactory.getLogger(StudentController.class);
	
    @Autowired
    StudentManager manager;
 
    @RequestMapping(value = "/getStudentInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getStudentInfo(HttpServletRequest req) {
    	String url = req.getRequestURI().substring(1);//
    	url = url.substring(url.indexOf("/"));
    	String serverHost = null;
    	StringBuffer buffer = new StringBuffer();
    	Map<String, String[]> parms = req.getParameterMap();
    	if(parms != null && !parms.isEmpty()){
    		buffer.append("?");
    		for(Entry<String, String[]> entry : parms.entrySet()){
	    		buffer.append(entry.getKey()).append("=").append(entry.getKey()).append("&");
	    	}
	    	buffer.deleteCharAt(buffer.length()-1);
    	}
    	
    	
    	try{
    		serverHost = getBestServerHost(3);
    	}catch(Exception e){
    		logger.error("获取服务器失败",e);
    		return "No server available, please try agen!";
    	}
    	String result = HttpConnection.doGetRequest(serverHost+url+buffer.toString(), "utf-8");
    	
        return "server result:"+result;
    }

	private String getBestServerHost() {
		Map<String, Integer> serverMap = ZookeeperClient.getServerHost();
		if(serverMap == null || serverMap.isEmpty())
			throw new RuntimeException("No server available!");
		List<Map.Entry<String,Integer>> list=new ArrayList<>();  
        list.addAll(serverMap.entrySet());  
        ValueComparator vc = new ValueComparator();  
        Collections.sort(list,vc);  
        logger.info("#######server host {},session size {}",list.get(0).getKey(),list.get(0).getValue());
		
		return list.get(0).getKey();
	}
	
	private String getBestServerHost(int strategy) {
		Map<String, Integer> serverMap = ZookeeperClient.getServerHost();
		if(serverMap == null || serverMap.isEmpty())
			throw new RuntimeException("No server available!");
		List<Map.Entry<String,Integer>> list=new ArrayList<>();  
		list.addAll(serverMap.entrySet());  
		ValueComparator vc = new ValueComparator();  
		Collections.sort(list,vc);  
		int serverIndex = 0;
		switch (strategy) {
		case 1:// 轮询
			serverIndex = 0;//调用一次累加一次，所以没被调用的是最小的排在第一个
			break;
		case 2:// ip 保持，未实现
			serverIndex = Math.abs(new Random().nextInt(list.size()));
			break;
		case 3:// 随机
			serverIndex = Math.abs(new Random().nextInt(list.size()));
			break;
		default:
			serverIndex = Math.abs(new Random().nextInt(list.size()));
			break;
		}
		
		logger.info("#######server host {},session size {}",list.get(serverIndex).getKey(),list.get(serverIndex).getValue());
		return list.get(serverIndex).getKey();
		
	}

}

class ValueComparator implements Comparator<Map.Entry<String, Integer>>{    
    public int compare(Map.Entry<String, Integer> mp1, Map.Entry<String, Integer> mp2)     
    {    
        return mp1.getValue() - mp2.getValue();    
    }    
}   
